
// 添加权限
function addPerm(){
    let reqData = new Map()
    const permId = $('#select-perm').val()
    const roleId = $('#modal-roleId').text()
    reqData['permId'] = permId
    reqData['roleId'] = roleId
    $.ajax({
        url: '/admin/perm/add',
        type: 'POST',
        data: JSON.stringify(reqData),
        dataType: 'JSON',
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            if (data['code'] === 1) {
                open_toast('success', '成功!')
            }
        }
    })
}
// 删除权限
function removePermOfRole(roleId, permId){
    let reqData = new Map()
    if(roleId == null){
        // 为null则表示在某个角色表单里进行删除操作，故从标签获取ID即可
        reqData['roleId'] = $('#modal-roleId').text()
    } else
        reqData['roleId'] = roleId
    if(permId == null){
        reqData['permId'] = $('#select-perm-id').val()
    } else reqData['permId'] = permId
    $.ajax({
        url: '/admin/perm/delete',
        type: 'POST',
        data: JSON.stringify(reqData),
        dataType: 'JSON',
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            open_toast(data['code'] === 1 ? 'success' : 'fail', data['message'])
        }
    })
}
// 渲染某个角色-权限列表页面
function renderPermInfo(permInfo){
    let $table = $('#tbody-perm')
    $table.html('')
    $.each(permInfo, (index, v) => {
        // 渲染权限列表
        let $perm = $(`<select></select>`)
        $.each(v['perms'], (index, perm) => {
            $perm.append(`
                <option value="${perm['id']}">${perm['id']}: ${perm['permName']}</option>
            `)
        })
        $table.append(`
        <tr class="text-center">
            <td>${v['id']}</td>
            <td>${v['roleName']}</td>
            <td><select id="select-perm-id" class="w-75"><option value="0">所有权限</option>`
            + $perm.html() +
            `</td>
            <td>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#div-modal" onclick="renderRolePerm(${v['id']})">编辑</button>
                <button class="btn btn-danger" onclick="removePermOfRole(${v['id']}, null)">删除</button>
            </td>
       </tr>
        `)
    })
}

// 渲染某个角色的所有权限页面
function renderRolePerm(id){
    let hasPerm = []
    // 根据角色ID查询信息
    $.ajax({
        url: '/admin/perm/query/' + id,
        type: 'POST',
        dataType: 'JSON',
        async: false,
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            console.log(data)
            if (data['code'] === 1) {
                $perm = $('#tbody-role-perm')
                $perm.html('')
                // 渲染基本信息
                $('#modal-roleId').text(data['response']['role']['id'])
                $('#modal-roleName').text(data['response']['role']['roleName'])
                $.each(data['response']['perms'], (index, v) => {
                    if(v == null)
                        return false
                    hasPerm.push(v['id'])
                    $perm.append(`
                <tr>
                    <td>${v['id']}</td>
                    <td>${v['permName']}</td>
                    <td><a href="#">${v['url']}</a></td>
                    <td><button class="btn btn-danger btn-sm" onclick="removePermOfRole(${data['response']['role']['id']}, ${v['id']})">删除</button></td>
                </tr>
                `)
                })
            }
        }
    })
    // 查询所有的权限信息（排除已经存在的权限）
    $.ajax({
        url: '/admin/perm/queryAllRolePerm',
        type: 'POST',
        dataType: 'JSON',
        async: false,
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            if (data['code'] === 1) {
                $('#select-perm').html('')
                $.each(data['response'], (index, v) =>{
                    // 不用渲染已经存在的权限
                    if(hasPerm.indexOf(v['id']) !== -1) {
                        return true;
                    }
                    $('#select-perm').append(`
                        <option value="${v['id']}">${v['id']}:${v['permName']}</option>
                    `)
                })
            } else open_toast('fail', data['response'])
        }
    })

}
// 加载所有权限数据
function loadPermData(){
    $.ajax({
        url: '/admin/perm/queryAllWithRole',
        type: 'POST',
        dataType: 'JSON',
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            console.log(data)
            if (data['code'] === 1) {
                // 生成权限信息
                renderPermInfo(data['response'])
            }
        }
    })
}
// 成功弹窗关闭后 -> 关闭模态框，并刷新窗口
$('#toast-success').bind('hidden.bs.toast', function () {
    $('#btn-modal-cancel').click()
    location.reload()
})

loadPermData()